package cn.trigram.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;

/**
 * 来自 {@link AbstractQueuedSynchronizer } 文档注释中的案例。
 * <br/>
 * 基于共享模式完成的互斥锁，类似{@link CountDownLatch}，非排他锁实现
 */
public class BooleanLatch {

  private static class Sync extends AbstractQueuedSynchronizer {

    boolean isSignalled() {

      return getState() != 0;
    }

    protected int tryAcquireShared(int ignore) {

      return isSignalled() ? 1 : -1;
    }

    protected boolean tryReleaseShared(int ignore) {

      setState(1);
      return true;
    }

  }

  private final Sync sync = new Sync();

  public boolean isSignalled() {

    return sync.isSignalled();
  }

  public void signal() {

    sync.releaseShared(1);
  }

  public void await() throws InterruptedException {

    sync.acquireSharedInterruptibly(1);
  }

}
